<template>
  <BaseContainer>
    <QueryFilter
      :model="queryFields"
      :label-col="{ style: { width: '70px' } }"
      @submit="queryPriceSheet"
      @reset="resetPriceSheet"
    >
      <a-form-item name="startTime" label="查价时间">
        <a-range-picker v-model:value="dateRange" value-format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>

      <a-form-item name="id" label="查价id">
        <a-input placeholder="请输入查价id" allow-clear v-model:value.trim="queryFields.id"></a-input>
      </a-form-item>
      <a-form-item name="platformNames" label="平台">
        <a-input placeholder="请输入平台名称" allow-clear v-model:value.trim="queryFields.platformNames"></a-input>
      </a-form-item>
      <a-form-item name="keyword" label="关键词">
        <a-input placeholder="请输入准确的关键词" allow-clear v-model:value.trim="queryFields.keyword"></a-input>
      </a-form-item>
      <a-form-item name="status" label="当前状态">
        <a-select v-model:value="queryFields.status" placeholder="请选择当前状态" :options="statusOptions" />
      </a-form-item>
      <a-form-item label="审核状态" name="approveStatus">
        <a-select
          v-model:value="queryFields.approveStatus"
          placeholder="请选择审核状态"
          :options="approveStatusOptions"
        />
      </a-form-item>
      <a-form-item label="产品" name="productId">
        <a-select v-model:value="queryFields.productId" placeholder="请选择产品" :options="productOptions" />
      </a-form-item>
      <a-form-item name="sellerName" label="销售员">
        <a-input placeholder="请输入销售员" allow-clear v-model:value.trim="queryFields.sellerName"></a-input>
      </a-form-item>
      <a-form-item name="type" label="类型">
        <a-select v-model:value="queryFields.type" placeholder="请选择类型" :options="typeOptions" />
      </a-form-item>
      <a-form-item name="industryId" label="行业">
        <industry-cascader
          v-model:industry-id="industryId"
          :industry-list="industryList"
          @change="handleIndustryChange"
        />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="查价列表">
      <a-button type="primary" class="mr-2" v-permission="[ADMIN, SALES, AGENT_BOSS]" @click="handleJump">
        <template #icon><plus-outlined /></template>
        新建查价
      </a-button>
      <export-excel-group
        group
        :col="columns"
        :data="tableData"
        v-permission="[OPERATION]"
        @on-export="handleExportExcel"
        @on-export-all="handleExportAllExcel"
      />
    </table-toolbar>
    <a-table
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 1000 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.key === 'tpType'">
          <a-tooltip placement="topLeft">
            <template #title>
              {{ record.tpType }}
            </template>
            <span class="over-hidden">{{ record.tpType || '--' }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'tpNotes'">
          <a-tooltip placement="topLeft">
            <template #title>
              {{ record.tpNotes }}
            </template>
            <span class="over-hidden">{{ record.tpNotes || '--' }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'id'">
          <span class="cursor-pointer" v-clipboard="record.id" v-clipboard:success="copySuccess">{{ record.id }}</span>
        </template>
        <template v-if="column.key === 'type'">
          {{ TypeKeyMap[text] }}
        </template>
        <template v-if="column.key === 'createTime'"> {{ formatDate(record.createTime) }} </template>
        <template v-if="column.key === 'areas'">
          <area-popover ellipsis :areas="text" :product-id="record.productId" />
        </template>
        <template v-if="column.key === 'approveStatus'">
          <a-badge
            v-if="text !== ApproveStatusEnum.FAIL"
            :status="ApproveStatusColor[text]"
            :text="ApproveStatusKeyMap[text]"
          />
          <a-tooltip v-else @visible-change="handleVisibleChange($event, record)">
            <template #title>审核意见：{{ record.failDesc }}</template>
            <a-badge :status="ApproveStatusColor[text]" :text="ApproveStatusKeyMap[text]" />
          </a-tooltip>
        </template>
        <template v-if="column.key === 'priceAskWordsStr'">
          <a-tooltip placement="topLeft">
            <template #title>
              {{ record.priceAskWordsStr }}
            </template>
            <span class="cursor-pointer" v-clipboard="record.priceAskWordsStr" v-clipboard:success="copySuccess">{{
              record.priceAskWordsStr
            }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'hzNotes'">
          <a-tooltip placement="topLeft">
            <template #title>
              {{ record.hzNotes }}
            </template>
            <span class="over-hidden">{{ record.hzNotes }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'status'">
          <a-badge :status="StatusColor[text]" :text="StatusKeyMap[text]" />
        </template>
        <template v-if="column.key === 'remark'">
          <span v-if="record.oldOrderId">续费词包：{{ record.oldOrderId }}</span>
          <span v-else>--</span>
        </template>
        <template v-if="column.key === 'operate'">
          <a-button
            type="primary"
            class="mr-2"
            v-permission="[OPERATION, ADMIN]"
            :class="{ 'bg-red-600': shouldTryApprove(record.approveStatus) }"
            @click="handleDetail(record, PermissionEnum.AUDIT)"
          >
            <span v-if="shouldTryApprove(record.approveStatus)">重审</span>
            <span v-else>审核</span>
          </a-button>

          <a-button
            type="primary"
            class="mr-2"
            v-if="showOrderBtn(record)"
            @click="handleDetail(record, PermissionEnum.ORDER)"
            v-permission="[AGENT_BOSS, AGENT, ADMIN]"
          >
            提单
          </a-button>
          <a-button @click="handleDetail(record, PermissionEnum.DETAIL)"> 详情</a-button>
        </template>
      </template>
    </a-table>
  </BaseContainer>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { computed, onActivated, onMounted, reactive, ref } from 'vue'
import { formatDate, toLabelValue } from '@/utils'
import TableToolbar from '@/components/table-toolbar/index.vue'
import getPriceSheet, { getAllPriceSheet, type PriceSheetQuery } from '@/services/price-sheet/getPriceSheet'
import { PlusOutlined } from '@ant-design/icons-vue'
import { usePriceSheetStore } from '@/store/usePriceSheetStore'
import { showOrderBtn } from '@/views/price-sheet/interface'
import type { TableProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useMainStore } from '@/store/useMainStore'
import { compact } from 'lodash-es'
import BaseContainer from '@/components/base-container/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import Divider from '@/components/divider/index.vue'
import { hasPermission } from '@/utils/permission'
import getPriceFailDesc from '@/services/price-sheet/getPriceFailDesc'
import AreaPopover from '@/components/area-popover/index.vue'
import { ApproveStatusColor, ApproveStatusKeyMap, StatusColor, StatusKeyMap } from '@/core/mapper/status'
import { ProductKeyMap } from '@/core/mapper/platform'
import { ProductEnum } from '@/core/enums/platform'
import { ApproveStatusEnum, StatusEnum } from '@/core/enums/status'
import { TypeKeyMap } from '@/core/mapper/type'
import { AuthEnum, PermissionEnum } from '@/core/enums/auth'
import type { PriceSheet } from '@/core/interfaces/priceSheet'
import ExportExcelGroup from '@/components/export-excel-group/index.vue'
import { useReloadModal } from '@/hooks/useReloadModal'
import getIndustryList from '@/services/order/getIndustryList'
import IndustryCascader from '@/components/industry-cascader/index.vue'
import { TypeEnum, LandingPageEnum, IsFromHjzwEnum, IsTPEnum } from '@/core/enums/type'
import moment from 'moment'
import dayjs from 'dayjs'
const { OPERATION, AGENT, AGENT_BOSS, SALES, ADMIN } = AuthEnum
useReloadModal()
const router = useRouter()
const mainStore = useMainStore()

const statusOptions = ref(toLabelValue(StatusKeyMap))
const approveStatusOptions = ref(toLabelValue(ApproveStatusKeyMap))
const productOptions = ref(toLabelValue(ProductKeyMap))
const typeOptions = ref(toLabelValue(TypeKeyMap))
const defaultValue = ref([
  moment().subtract(10, 'days'), // 10天前的日期
  moment() // 当前日期
])
// 获取当前时间
const now = new Date()
const currentDateTime = computed(() => formatDateus(now))
//
// 获取当前时间往前10天的时间
const tenDaysAgo = new Date()
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10)
const tenDaysAgoDateTime = computed(() => formatDateus(tenDaysAgo))

// 辅助函数，用于格式化日期
function formatDateus(date) {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hour = date.getHours().toString().padStart(2, '0')
  const minute = date.getMinutes().toString().padStart(2, '0')
  const second = date.getSeconds().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}
const defaultQueryFields = () => ({
  id: undefined,
  productId: ProductEnum.All,
  status: statusOptions.value[0].value,
  sellerName: '',
  keyword: '',
  platformNames: '',
  industryCode: undefined,
  type: TypeEnum.ALL,
  sellerId: mainStore.sellerId,
  proxyId: mainStore.proxyId,
  approveStatus: ApproveStatusEnum.ALL,
  startTime: tenDaysAgoDateTime.value,
  endTime: currentDateTime.value
})
// startTime: queryFields.startTime === undefined ? tenDaysAgoDateTime.value : queryFields.startTime,
// endTime: queryFields.endTime === undefined ? currentDateTime.value : queryFields.endTime
const dateRange = computed({
  set(val: string[]) {
    if (val) {
      const [startTime, endTime] = val
      queryFields.startTime = startTime
      queryFields.endTime = endTime
    } else {
      queryFields.startTime = ''
      queryFields.endTime = ''
    }
  },
  get() {
    if (queryFields.startTime && queryFields.endTime) {
      return [queryFields.startTime, queryFields.endTime]
    } else {
      return []
    }
  }
})
//
const industryId = ref<number | undefined>()
const queryFields = reactive<PriceSheetQuery>(defaultQueryFields())

const priceSheetStore = usePriceSheetStore()
const [, fetchPriceSheet, loading] = getPriceSheet()
const [, fetchAllPriceSheet] = getAllPriceSheet()
const [, fetchPriceFailDesc] = getPriceFailDesc()
const [industryList, fetchIndustryList] = getIndustryList()

const columns = computed<TableProps['columns']>(() => {
  return compact([
    {
      title: '查价id',
      dataIndex: 'id',
      key: 'id',
      width: '150px'
    },
    {
      title: '平台',
      dataIndex: 'platformNames',
      key: 'platformNames',
      width: '150px',
      customRender: ({ text }) => {
        return text || '--'
      }
    },
    {
      title: '关键词',
      dataIndex: 'priceAskWordsStr',
      key: 'priceAskWordsStr',
      width: '150px',
      ellipsis: true
    },
    // {
    //   title: '标王编号',
    //   dataIndex: 'zzbwOrderNo',
    //   key: 'zzbwOrderNo',
    //   width: '150px'
    // },
    // {
    //   title: '套餐',
    //   dataIndex: 'comboName',
    //   key: 'comboName',
    //   width: '200px',
    //   customRender: ({ text }) => {
    //     return text || '--'
    //   }
    // },
    // {
    //   title: '产品',
    //   dataIndex: 'productName',
    //   key: 'productName',
    //   width: '100px',
    //   customRender: ({ text }) => {
    //     return text || '--'
    //   }
    // },
    {
      title: '审核状态',
      dataIndex: 'approveStatus',
      key: 'approveStatus',
      width: '150px'
    },
    {
      title: '审核意见',
      dataIndex: 'approveInfo',
      key: 'approveInfo',
      width: '200px',
      customRender: ({ text }: { text: string }) => {
        if (!text) {
          return '--'
        }
        return text
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '160px'
    },
    {
      title: '行业',
      dataIndex: 'industryName',
      key: 'industryName',
      width: '150px',
      customRender: ({ text }) => {
        if (!text) {
          return '--'
        }
        return text
      }
    },
    {
      title: '查价日期',
      dataIndex: 'createTime',
      key: 'createTime',
      width: '200px'
    },
    hasPermission([OPERATION, ADMIN]) && {
      title: '最后审核人',
      dataIndex: 'approverName',
      key: 'approverName',
      width: '150px',
      customRender: ({ text }) => {
        if (!text) {
          return '--'
        }
        return text
      }
    },
    hasPermission([OPERATION, AGENT, AGENT_BOSS, ADMIN]) && {
      title: '投放区域',
      dataIndex: 'areas',
      key: 'areas',
      ellipsis: true,
      width: '150px',
      customRender: ({ record, text }: { record: PriceSheet; text: string }) => {
        if (record.productId === ProductEnum.BW || record.productId === ProductEnum.BWYXB) {
          return text
        }
        return '全国'
      }
    },
    {
      title: '投放时长',
      dataIndex: 'comboPriceName',
      key: 'comboPriceName',
      width: '150px',
      customRender: ({ text }) => {
        return text || '--'
      }
    },
    {
      title: '投放时间段',
      dataIndex: 'onLinePeriod',
      key: 'onLinePeriod',
      width: '150px',
      customRender: ({ record, text }: { record: PriceSheet; text: string }) => {
        if (record.productId === ProductEnum.BW || record.productId === ProductEnum.BWYXB) {
          return text || '--'
        } else {
          return '7*24小时'
        }
      }
    },
    hasPermission([OPERATION, AGENT_BOSS, ADMIN]) && {
      title: '代理商',
      dataIndex: 'proxyName',
      key: 'proxyName',
      width: '200px'
    },
    // hasPermission([OPERATION, AGENT_BOSS, AGENT, SALES, ADMIN]) && {
    //   title: '市场价',
    //   dataIndex: 'marketPrice',
    //   key: 'marketPrice',
    //   width: '150px',
    //   customRender: ({ record }: { record: PriceSheet }) => {
    //     if (
    //       record.productId === ProductEnum.CiBao ||
    //       record.productId === ProductEnum.CBYXB ||
    //       record.productId === ProductEnum.HJBW
    //     ) {
    //       if (record.comboPrice) {
    //         return record.comboPrice
    //       } else {
    //         return '--'
    //       }
    //     }
    //     if (record.marketPrice) {
    //       return record.marketPrice
    //     } else if (record.assessmentPrice) {
    //       return record.assessmentPrice
    //     } else {
    //       return '--'
    //     }
    //   }
    // },
    // hasPermission([OPERATION, AGENT_BOSS, AGENT, ADMIN]) && {
    //   title: '提单价',
    //   dataIndex: 'assessmentPrice',
    //   key: 'assessmentPrice',
    //   width: '150px',
    //   customRender: ({ record }: { record: PriceSheet }) => {
    //     if (record.assessmentPrice) {
    //       return record.assessmentPrice
    //     } else if (record.comboPrice) {
    //       return record.comboPrice
    //     } else {
    //       return '--'
    //     }
    //   }
    // },
    //
    /*





*/

    hasPermission([OPERATION, AGENT_BOSS, AGENT, SALES, ADMIN]) &&
      mainStore.userInfo?.proxy_id !== 1377 &&
      mainStore.userInfo?.proxy_id !== 1407 && {
        title: '市场价',
        dataIndex: 'marketPrice',
        key: 'marketPrice',
        width: '150px',
        customRender: ({ record }: { record: PriceSheet }) => {
          // 判断 productId 是否为 2,6,7,9,10
          if ([2, 6, 7, 9, 10].includes(record.productId)) {
            return record.comboPrice || '--'
          }

          // 原有的词包等产品的逻辑
          if (
            record.productId === ProductEnum.CiBao ||
            record.productId === ProductEnum.CBYXB ||
            record.productId === ProductEnum.HJBW
          ) {
            return record.comboPrice || '--'
          }

          if (record.marketPrice) {
            return record.marketPrice
          } else if (record.assessmentPrice) {
            return record.assessmentPrice
          } else {
            return '--'
          }
        }
      },
    hasPermission([OPERATION, AGENT_BOSS, AGENT, ADMIN]) &&
      mainStore.userInfo?.proxy_id !== 1377 &&
      mainStore.userInfo?.proxy_id !== 1407 && {
        title: '提单价',
        dataIndex: 'assessmentPrice',
        key: 'assessmentPrice',
        width: '150px',
        customRender: ({ record }: { record: PriceSheet }) => {
          // 判断 productId 是否为 2,6,7,9,10
          if ([2, 6, 7, 9, 10].includes(record.productId)) {
            return record.marketPrice || '--'
          }

          if (record.assessmentPrice) {
            return record.assessmentPrice
          } else if (record.comboPrice) {
            return record.comboPrice
          } else {
            return '--'
          }
        }
      },

    hasPermission([OPERATION, AGENT_BOSS, AGENT, ADMIN]) && {
      title: '销售人员',
      dataIndex: 'sellerName',
      key: 'sellerName',
      width: '150px'
    },
    {
      title: '提单状态',
      dataIndex: 'status',
      key: 'status',
      width: '150px'
    },
    // {
    //   title: '落地页',
    //   dataIndex: 'shopType', // LandingPageEnum
    //   key: 'shopType',
    //   width: '150px',
    //   customRender: ({ record }: { record: PriceSheet }) => {
    //     return record.shopType === LandingPageEnum.Shop
    //       ? '店铺'
    //       : record.shopType === LandingPageEnum.SinglePage
    //       ? '单页'
    //       : '--'
    //   }
    // },
    // {
    //   title: '黄展转移',
    //   dataIndex: 'hzTransferCode',
    //   key: 'hzTransferCode',
    //   width: '80px',
    //   customRender: ({ record }: { record: PriceSheet }) => {
    //     return record.hzTransferCode === IsFromHjzwEnum.Yes ? '是' : '否'
    //   }
    // },
    // {
    //   title: '转移备注',
    //   dataIndex: 'hzNotes',
    //   key: 'hzNotes',
    //   width: '150px',
    //   ellipsis: true
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: '150px',
      ellipsis: true
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '是否特批',
      dataIndex: 'tpCode',
      key: 'tpCode',
      width: '100px',
      customRender: ({ record }: { record: PriceSheet }) => {
        return record.tpCode === IsTPEnum.Yes ? '特批' : '常规'
      }
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '类型',
      dataIndex: 'tpType',
      key: 'tpType',
      width: '150px',
      ellipsis: true
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '特批备注',
      dataIndex: 'tpNotes',
      key: 'tpNotes',
      width: '150px',
      ellipsis: true
    },
    hasPermission([OPERATION, AGENT_BOSS]) && {
      title: '优惠金额',
      dataIndex: 'tpAmount',
      key: 'tpAmount',
      width: '100px',
      ellipsis: true
    },

    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      width: '160px'
    }
  ])
})

const shouldTryApprove = (status: ApproveStatusEnum) => {
  return [ApproveStatusEnum.SUCCESS, ApproveStatusEnum.FAIL].includes(status)
}

const tableData = ref<PriceSheet[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

async function loadPriceSheet() {
  const [err, res] = await fetchPriceSheet({
    ...queryFields,
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    id: queryFields.id || 0,
    industryCode: queryFields.industryCode || 0,
    startTime: queryFields.startTime === undefined ? tenDaysAgoDateTime.value : queryFields.startTime,
    endTime: queryFields.endTime === undefined ? currentDateTime.value : queryFields.endTime
    // startTime: '默认今天',
    // endTime: '默认10天前'currentDateTime
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
    tableData.value = res.data.data.priceAsks
  }
}

function handleIndustryChange() {
  queryFields.industryCode = industryList.value.find((item) => item.id === industryId.value)?.code
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadPriceSheet()
}

function queryPriceSheet() {
  pagination.pageSize = 15
  pagination.current = 1
  loadPriceSheet()
}

function resetPriceSheet() {
  Object.assign(queryFields, defaultQueryFields())
  industryId.value = undefined
  pagination.pageSize = 15
  pagination.current = 1
  loadPriceSheet()
}

function handleDetail(row: PriceSheet, permission: PermissionEnum) {
  priceSheetStore.setCurrentPriceSheet(row)
  priceSheetStore.setDetailPagePermission(permission)

  if (row.productId === 7) {
    router.push({ name: 'price-detail', query: { moveUp: row.moveUp } })
  } else {
    router.push({ name: 'price-detail' })
  }
}

function handleExportExcel(exportExcel: Function) {
  exportExcel(`查价列表${Date.now()}`, {
    type: (value: TypeEnum) => TypeKeyMap[value],
    status: (value: StatusEnum) => StatusKeyMap[value],
    approveStatus: (value: ApproveStatusEnum) => {
      if (value === ApproveStatusEnum.ALL) {
        return '--'
      }
      return ApproveStatusKeyMap[value]
    }
  })
}

async function handleExportAllExcel(exportExcel: Function) {
  const [err, res] = await fetchAllPriceSheet({
    pageNum: 1,
    pageSize: 9999999,
    ...queryFields,
    id: queryFields.id || 0,
    industryCode: queryFields.industryCode || 0,
    startTime: queryFields.startTime,
    endTime: queryFields.endTime
    // startTime: '默认今天',
    // endTime: '默认10天前'
  })

  if (!err) {
    exportExcel(
      `查价列表${Date.now()}`,
      {
        type: (value: TypeEnum) => TypeKeyMap[value],
        status: (value: StatusEnum) => StatusKeyMap[value],
        approveStatus: (value: ApproveStatusEnum) => {
          if (value === ApproveStatusEnum.ALL) {
            return '--'
          }
          return ApproveStatusKeyMap[value]
        }
      },
      res.data.data.priceAsks
    )
  }
}

async function handleVisibleChange(visible: boolean, record: PriceSheet) {
  if (!record.failDesc) {
    if (visible) {
      const [err, res] = await fetchPriceFailDesc({
        priceAskId: record.id
      })

      if (!err) {
        record.failDesc = res.data.data.approveInfo
      }
    }
  }
}

function handleJump() {
  router.push({
    name: 'price-package'
  })
}

function copySuccess() {
  message.success('复制成功')
}

onMounted(() => {
  fetchIndustryList()
})

onActivated(() => {
  loadPriceSheet()
})
</script>

<script lang="ts">
export default {
  name: 'PriceManager'
}
</script>

<style scoped lang="scss">
.over-hidden {
  display: block;
  width: 140px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
